#include <iostream>
#include <fstream>
#include "contacts.pb.h"

const std::string filename = "../contacts.bin";

void AddPeopleInfo(contacts::PeopleInfo* people)
{
    std::cout << "请输入联系人姓名:";
    std::string name;
    std::getline(std::cin, name);
    people->set_name(name);

    // std::cout << "请输入联系人年龄:";
    // int age;
    // std::cin >> age;
    // people->set_age(age);

    std::cout << "请输入联系人生日:";
    int birthday;
    std::cin >> birthday;
    people->set_birthday(birthday);

    std::cin.ignore(256, '\n'); // 清空缓冲区信息
    for (int i = 0; ; i++)
    {
        std::cout << "请输入联系人电话" << i + 1 << "(输入回车完成电话新增):";
        std::string number;
        std::getline(std::cin, number);
        if (number.empty())
            break;
        contacts::PeopleInfo_Phone* phone = people->add_phones();
        phone->set_number(number);
    }
    std::cout << "添加联系人成功..." << std::endl;
}

int main()
{
    contacts::Contacts contacts;
    std::fstream input(filename, std::ios::in | std::ios::binary);
    if (!input)
    {
        std::cout << filename << " not found, create new file!" << std::endl;
    }
    else if (!contacts.ParseFromIstream(&input))
    {
        std::cout << "parse error..." << std::endl;
        input.close();
        return 2;
    }

    AddPeopleInfo(contacts.add_contacts());

    std::fstream output(filename, std::ios::out | std::ios::trunc | std::ios::binary);
    if (!contacts.SerializePartialToOstream(&output))
    {
        std::cout << "serialize error..." << std::endl;
        input.close();
        output.close();
        return 3;
    }

    std::cout << "write success..." << std::endl;
    input.close();
    output.close();
    return 0;
}